<script setup>
import {ref} from 'vue';
import {ElMessage} from 'element-plus';
import {updateCategoryApi} from '@/service/goods.js'; // 假设你有一个添加分类的 API

const emit = defineEmits(['reload']);
const reload = () => {
  emit('reload');
}

const drawerVisible = ref(false);
const ruleForm = ref({
  title: '',
  sort: ''
  // 其他分类信息字段
});

// 初始化form
const resetForm = () => {
  ruleForm.value = {
    id:'',
    title: '',
    table_name: '',
    sort: 0
    // 其他分类信息字段
  };
};

const rules = ref({
  id: [
    {required: true, message: '数据异常，请刷新重试'},
  ],
  title: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
  ],
  // 其他验证规则
});


// 显示添加分类的抽屉，并清空表单
const showDrawer = (row) => {
  drawerVisible.value = true;
  ruleForm.value = row;
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
  // 初始化
  resetForm();
};

// 提交表单
const ruleFormRef = ref(null);
const doSubmit = async () => {
  // 验证并提交表单
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await updateCategoryApi(ruleForm.value);
        if (res.code === 200) {
          ElMessage.success(res.msg);
          closeDrawer();
          reload();
        }
      } catch (error) {
        // 提示
        ElMessage.error('添加分类失败');
      }
    } else {
      // 提示
      ElMessage.error('表单验证失败');
    }
  });
};

defineExpose({
  showDrawer
});
</script>

<template>
  <el-drawer
      title="更新商品分类"
      v-model="drawerVisible"
      size="20%"
      header-class="drawer-header"
  >
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" label-position="top">
      <el-form-item label="分类名称" prop="title">
        <el-input v-model="ruleForm.title" placeholder="请输入分类名称"></el-input>
      </el-form-item>
      <el-form-item label="表名" prop="table_name">
        <el-input v-model="ruleForm.table_name" placeholder="请输入表名"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" placeholder="请输入排序"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSubmit">提交</el-button>
        <el-button @click="closeDrawer">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="less">
.drawer-header {
  background-color: #f0f2f5;
}
</style>
